package com.itheima.mp.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDto;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.query.PageQuery;
import com.itheima.mp.query.UserQuery;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void deductBalance(Long id, Integer money) {
        //1.查询用户信息
        User user = getById(id);
        //2.判断用户状态
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态有误");
        }
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        //3.修改用户状态
        lambdaUpdate()
                .set(User::getBalance, user.getBalance() - money)
                .set(user.getBalance() - money == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) //乐观锁
                .update();
    }

    @Override
    public List<UserVO> getUsers(String name, Integer status, Integer maxBalance, Integer minBalance) {
        List<User> users = lambdaQuery().like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @Override
    public UserVO getUserAndAddresses(Long id) {
        //1.根据id查询用户信息
        User user = getById(id);
        //2.判断用户状态
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        //3.查询用户地址列表
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        //4.对象属性拷贝
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //如果地址不为空，则将地址列表设置到vo中
        if (CollUtil.isNotEmpty(addresses)) {
            //地址po转换成vo
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> getUsersAndAddresses(List<Long> ids) {
        //1.根据用户ids查询用户列表
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }

        //2.查询地址列表
        //2.1获取用户列表对应的id列表
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.2根据用户id查询地址列表
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        //2.3将地址集合po 转换成vo
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4将地址集合根据用户id分组
        Map<Long, List<AddressVO>> listMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        //3.将po转换成vo
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            //对象属性拷贝
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            //设置地址列表volist
            userVO.setAddresses(listMap.get(user.getId()));
            //添加到集合中
            list.add(userVO);
        }
        return list;
    }

    @Override
    public PageDto<UserVO> getUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        //1.构造分页条件
        Page<User> page = new PageQuery().toMpPageSortByUpdateTime();

        //2.分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        //3.构造返回值vo
        return PageDto.ToPageDto(p, UserVO.class);
    }
}
